package com.jzoffer;

import java.util.Arrays;

public class AdjustArrayOrder {
    public static void main(String[] args) {
        int[] num = {2,4,3,6,5,6,4,9,4,1};
        reOrderArray2(num);
        System.out.println(Arrays.toString(num));

    }

    // 拷贝数组法
    public static void reOrderArray(int [] array){
        if(array == null || array.length < 1){
            return;
        }
        int length = array.length;
        int oddNum = 0;
        for(int num:array){
            if((num & 1) == 1){
                oddNum++;
            }
        }
        int[] copy = array.clone();
        int i = 0;
        int j = oddNum;
        for (int num:copy){
            if((num & 1) == 1){
                array[i++] = num;
            }else{
                array[j++] = num;
            }
        }

    }

    // 冒泡算法，前偶后奇数就交换
    public static void reOrderArray2(int [] array){
        if(array == null || array.length < 1){
            return;
        }
        for (int i = 0; i < array.length; i++) {
            for(int j = array.length - 1; j > i;j--){
                if((array[j] & 1) == 1 && (array[j-1] & 1) == 0 ){
                    swap(array,j,j - 1);
                }
            }
        }

    }

    public static void swap(int[] array,int i ,int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}
